package com.xixilala.video.views

import android.content.Context
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.TextureView
import com.xixilala.video.App
import com.xixilala.video.util.CameraUtil
import com.xixilala.video.util.LogUtil

class CameraTextureView:TextureView, TextureView.SurfaceTextureListener {

    private val buffer = ByteArray(1080*1080*3/2)

    private var camera: Camera? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initCamera()
    }

    private fun initCamera() {
        surfaceTextureListener = this
    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {

        Camera.open(0).apply {
            val cameraParam = parameters
            cameraParam?.run {
                setPreviewSize(1080,1080)
                previewFormat = ImageFormat.NV21
            }
            parameters = cameraParam

            setDisplayOrientation(CameraUtil.calculateCameraPreviewOrientation(App.appContext,0))
            setPreviewTexture(surface)

            addCallbackBuffer(buffer)
            setPreviewCallbackWithBuffer(object : Camera.PreviewCallback{
                override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
                    LogUtil.d("data = ${data?.get(0)}")
                    camera?.addCallbackBuffer(data) // 保证每次都会回调
                }
            })

            startPreview()

        }
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {

    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        camera?.stopPreview()
        camera?.release()
        return true
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {

    }
}